package com.ideal.manage.esms.service.system;

import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.sys.*;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.system.UserRepository;
import com.ideal.manage.esms.util.HttpRequests;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@CacheConfig( cacheNames = "userCache")
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleService roleService;
    @Autowired
    private CustomerService customerService;

    @Autowired
    private UserProjectService userProjectService;

    @Autowired
    private RoleMenuService roleMenuService;

//    public Page<User> findAll(int pageNum, HttpServletRequest request){
//        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request,"Q_");
//        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
//        SpecificationOperator operator = new SpecificationOperator("delFlag","0","EQ");
//        operators.add(operator);
//        MySpecification<User> mySpecifications = new MySpecification<>(operators);
//        Pageable pageable = new PageRequest(pageNum,15,sort);
//        Page<User> page = userRepository.findAll(mySpecifications,pageable);
//        return page;
//    }

    /**
     * 分页排序查询用户列表
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findAllUsers(int pageNum, HttpServletRequest request){
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request,"Q_");
        Object value = null;
        String oper = "";
        String key="";
        List<SpecificationOperator> operatorList =new ArrayList<>();
        for (SpecificationOperator operator : operators) {
            if (operator.getKey().equals("role")) {
                value = operator.getValue();
                oper = operator.getOper();
                operatorList.add(new SpecificationOperator("role.id", value, oper));
            }else{
                value = operator.getValue();
                oper = operator.getOper();
                key= operator.getKey();
                operatorList.add(new SpecificationOperator(key, value, oper));
            }
        }

        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        SpecificationOperator operator = new SpecificationOperator("delFlag","0","EQ");
        operatorList.add(operator);
        MySpecification<User> mySpecifications = new MySpecification<>(operatorList);
        Pageable pageable = new PageRequest(pageNum,15,sort);
        Page<User> page = userRepository.findAll(mySpecifications,pageable);
        List<User> users=page.getContent();


        List<User> newUsers=new ArrayList<>();
        for(User user:users){
            String projectStr="";
            List<UserProject> userProjects =userProjectService.findProjects(user.getId());
            List<Menu> menus=roleMenuService.findMenusByRole(user.getRole());
           if(userProjects.size()>0) {
               for(UserProject userProject:userProjects){
                   projectStr+=userProject.getProjectId().getName()+"|";
               }
               projectStr=projectStr.substring(0,projectStr.lastIndexOf("|"));
           }
            else{
               projectStr="未配置";
           }
            user.setMenus(menus);
            user.setProjectStr(projectStr);
            newUsers.add(user);
        }
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(newUsers);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 根据用户名和密码寻找用户
     * @param loginName
     * @param password
     * @return
     */
    public User findByLoginNameAndPassword(String loginName,String password){
        User user = userRepository.findByLoginNameAndPassword(loginName,password);
        return user;
    }

    /**
     * 根据ID获取user
     * @param id
     * @return
     */
    public User findById (String id){
        User user = userRepository.findOne(id);
        return user;
    }

    /**
     * 保存用户
     * @param id
     * @param loginName
     * @param password
     * @param checkPassword
     * @param role
     * @return
     */
    public User saveUser(String id, String loginName, String password,String changePassword,
                         String checkPassword, String role){
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = new User();
        if(id != null){
            user = findById(id);
            if(role != null){
                Role r = roleService.findById(role);
                if("admin".equals(r.getName())){
                    user.setLastUpdateUser(null);
                }else{
                    user.setLastUpdateUser(new User(shiroUser.getId()));
                }
                user.setRole(r);
                user.setLastUpdateTime(new Date());
            }
        }else {
            Role r = roleService.findById(role);
            user.setRole(r);
            user.setCreateTime(new Date());
            user.setCreateUser(new User(shiroUser.getId()));
            user.setDelFlag(0L);
        }
        user.setLoginName(loginName);
        user.setPassword(password);
        user.setChangePassword(changePassword);
        userRepository.save(user);
        return user;
    }

    /**
     * 批量删除用户
     * @param ids
     */
    public void delUser(String [] ids){
        List<User> users = userRepository.findAll(Arrays.asList(ids));
        for(User user : users){
            user.setDelFlag(1L);
        }
        userRepository.save(users);
    }

    /**
     * 获取指定身份名称的用户
     * @param name
     */
    public List<User> findByParameterName(String name){
        List<Role> roles = roleService.findByType(name);
        List<User> users = userRepository.findByRoleIn(roles);
        return users;
    }


    public void save(User user){
        userRepository.save(user);
    }

    /**
     * 修改当前登录用户的密码
     * @param password
     * @return
     */
    public String passwordSave(String password) {
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        user.setPassword(password);
        userRepository.save(user);
        return "保存成功";
    }
}
